﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace SCG.TurboSprite
{
    [ToolboxBitmap(typeof(CompassNavigator), "CompassNavigator")]
    public class CompassNavigator : Control
    {
        //constructor
        public CompassNavigator()
        {
            Cursor = Cursors.Cross;
        }

        //Should be assigned to a SpriteSurface
        public SpriteSurface Surface
        {
            get
            {
                return _surface;
            }
            set
            {
                if (_surface != null)
                    _surface.BeforeAnimationCycle -= BeforeAnimationCycle;
                _surface = value;
                if (_surface != null)
                    _surface.BeforeAnimationCycle += BeforeAnimationCycle;
            }
        }

        //Render the BackgroundImage
        protected override void OnPaint(PaintEventArgs e)
        {
            if (BackgroundImage == null)
            {
                //if no image assigned, show quadrants
                e.Graphics.Clear(BackColor);
                Pen p = new Pen(ForeColor, 2);
                e.Graphics.DrawRectangle(p, Bounds);
                e.Graphics.DrawLine(p, Width / 2, 0, Width / 2, Height);
                e.Graphics.DrawLine(p, 0, Height / 2, Width, Height / 2);
            }
            else
                e.Graphics.DrawImage(BackgroundImage, 0, 0, Width, Height);
        }
        protected override void OnPaintBackground(PaintEventArgs pevent)
        {                      
        }

        //Mouse handling
        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
            _scrolling = true;
            _x = e.X;
            _y = e.Y;
        }
        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            _x = e.X;
            _y = e.Y;
        }
        protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseUp(e);
            _scrolling = false;       
        }

        //Our hook into the SpriteSurface's cycle
        private void BeforeAnimationCycle(object sender, EventArgs e)
        {
            if (_scrolling && Surface != null)
            {
                int signHorz = _x < Width / 2 ? -1 : 1;
                int signVert = _y < Height / 2 ? -1 : 1;
                int distHorz = Math.Abs(_x - Width / 2);
                int distVert = Math.Abs(_y - Height / 2);
                Surface.OffsetX += distHorz * signHorz;
                Surface.OffsetY += distVert * signVert;
            }
        }

        //private members
        private bool _scrolling = false;
        private SpriteSurface _surface = null;
        private int _x = 0;
        private int _y = 0;
    }
}
